package com.iplant.ams.serviceImpl.dao.dms;

import com.iplant.ams.service.basicenum.dms.scada.DMSDataClass;
import com.iplant.ams.service.basicenum.dms.scada.DMSDataTypes;
import com.iplant.ams.service.po.dms.DMSDeviceType;
import com.iplant.ams.service.po.dms.scada.alarm.DMSDeviceAlarm;
import com.iplant.ams.service.po.dms.scada.alarm.DMSDeviceAlarmFrequency;
import com.iplant.ams.service.po.dms.scada.alarm.DMSDeviceAlarmStatistics;
import com.iplant.ams.service.po.dms.scada.conf.DMSDeviceParameter;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.DBEnumType;
import com.iplant.base.po.enums.DBSchemas;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.annotation.dao.DBBaseDAO;
import com.iplant.base.utils.general.CalendarTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.basicenum.stat.StatTypes;
import com.iplant.basic.service.po.bms.BMSEmployee;
import lombok.extern.slf4j.Slf4j;

import java.util.*;


@Slf4j
@DBBaseDAO(DMSDeviceParameter.class)
public class DMSDeviceParameterDAO extends BaseDAO {

    private static DMSDeviceParameterDAO Instance = null;

    private DMSDeviceParameterDAO() {
        super("");
        this.Init();
    }

    public static DMSDeviceParameterDAO getInstance() {
        if (Instance == null)
            Instance = new DMSDeviceParameterDAO();
        return Instance;
    }

    public List<DMSDeviceParameter> DMS_SelectDeviceParameterList(BMSEmployee wLoginUser, int wDeviceID, String wDeviceNo,
                                                                  String wAssetNo, int wDataClass, Pagination wPagination, OutResult<Integer> wErrorCode) {


        Map<String, Object> wMap = new HashMap<>();
        wMap.put("DeviceID", wDeviceID);
        wMap.put("DeviceCode", wDeviceNo);
        wMap.put("AssetNo", wAssetNo);
        wMap.put("DataClass", wDataClass);
        return this.SelectPOList(wLoginUser, wMap, DMSDeviceParameter.class, wPagination, wErrorCode);
    }


    ///// <summary>
    ///// 根据参数字典配置初始化表结构
    ///// </summary>
    ///// <param name="wLoginUser"></param>
    ///// <param name="wDataClass">配置数据类</param>
    ///// <param name="wTableName">存储数据表名</param>
    ///// <param name="wErrorCode"></param>
    ///// <returns></returns>
    //public void DMS_InitDeviceTable(BMSEmployee wLoginUser, int wDataClass, String wTableName, OutResult<Integer> wErrorCode)
    //{

    //    try
    //    {

    //        String wVariableName = "VariableName";
    //        String wDataLength = "DataLength";
    //        String wName = "Name";


    //        String wSQL = StringUtils.Format("SELECT {1},{2},{3} FROM {0}.dms_device_parameter where DataClass=:wDataClass group by VariableName;",
    //            getDBName(), wVariableName, wDataLength, wName);
    //        Map<String, Object> wParamMap = new HashMap<String, Object>();
    //        wParamMap.put("wDataClass", wDataClass);
    //        List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);
    //        Map<String, Map<String, Object>> wResult = new HashMap<String, Map<String, Object>>();
    //        String wVariableNameTemp = "";
    //        for (Map<String, Object> wReader : wQueryResult)
    //        {
    //            if (!wReader.containsKey(wVariableName))
    //                continue;
    //            wVariableNameTemp = StringUtils.parseString(wReader.get(wVariableName));
    //            if (wResult.containsKey(wVariableNameTemp))
    //                continue;

    //            if (!wReader.containsKey(wDataLength) || StringUtils.parseInt(wReader.get(wDataLength)) < 10)
    //                wReader.get(wDataLength) = 20;

    //            if (!wReader.containsKey(wName) || StringUtils.isEmpty(StringUtils.parseString(wReader.get(wName))))
    //                wReader.get(wName) = wVariableNameTemp;

    //            wResult.add(wVariableNameTemp, wReader);
    //        }

    //        List<String> wOwnList = this.QueryTableStruct(this.SQLType, wTableName, getDBName());
    //        if (wOwnList != null && wOwnList.size() > 0)
    //        { 
    //            for (String wString : wOwnList)
    //            {
    //                if (wResult.containsKey(wString))
    //                    wResult.Remove(wString);
    //            }
    //        }


    //        List<String> wFieldList = new ArrayList<String>();

    //        for (String wColName : wResult.keySet())
    //        {
    //            switch (this.SQLType)
    //            {
    //                case Default:
    //                case MySQL:
    //                    wFieldList.add(StringUtils.Format(" ADD COLUMN `{0}` VARCHAR({1}) NOT NULL DEFAULT '''' COMMENT ''{2}'' ", wColName, wResult.get(wColName).get(wDataLength), wResult.get(wColName).get(wName)));
    //                    break;
    //                case SQLServer:
    //                    wFieldList.add(StringUtils.Format(" ADD [{0}] NVARCHAR({1}) NOT NULL DEFAULT ''''", wColName, wResult.get(wColName).get(wDataLength)));
    //                    break;
    //                case Oracle:
    //                    break;
    //                case Access:
    //                    break;
    //                default:
    //                    break;
    //            }


    //        }
    //        if (wFieldList.size() <= 0)
    //            return;


    //        String wSql = StringUtils.Format("ALTER TABLE {0}.{1} {2};", getDBName(), wTableName, StringUtils.Join(",", wFieldList));

    //        this.update(wSql, null);


    /// <summary>
    /// 根据参数字典配置初始化表结构
    /// </summary>
    /// <param name="wLoginUser"></param>
    /// <param name="wDataClass">配置数据类</param>
    /// <param name="wModelID">配置设备型号ID</param>
    /// <param name="wDeviceCode">配置设备型号Code</param>
    /// <param name="wErrorCode"></param>
    public void DMS_InitDeviceTable(BMSEmployee wLoginUser, int wDataClass, int wDataGrad, int wDeviceID, String wDeviceCode, OutResult<Integer> wErrorCode) {

        try {
            if (wDataClass <= 0 || wDeviceID <= 0 || StringUtils.isEmpty(wDeviceCode))
                return;


            String wVariableName = "VariableName";
            String wDataLength = "DataLength";
            String wName = "Name";
            String wDataType = "DataType";


            String wSQL = StringUtils.Format("SELECT t.{1},t.{2},t.{3},t.{4}  FROM {0}.dms_device_parameter t " +
                            " inner join {0}.dms_device_ledger t1 on t.DeviceID=t1.ID " +
                            " where t.ID>0 AND  t.DataClass=:wDataClass  and t1.ID= :wDeviceID " +
                            " and (:wDataGrad <0 or t.DataGrad=:wDataGrad ) " +
                            " and t.Active=1 group by t.VariableName;",
                    getDBName(), wVariableName, wDataLength, wName, wDataType);
            Map<String, Object> wParamMap = new HashMap<String, Object>();
            wParamMap.put("wDataClass", wDataClass);
            wParamMap.put("wDataGrad", wDataGrad);
            wParamMap.put("wDeviceID", wDeviceID);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);

            if (wQueryResult.size() <= 0)
                return;

            Map<String, Map<String, Object>> wResult = new HashMap<String, Map<String, Object>>();
            String wVariableNameTemp = "";
            String wTableName = StringUtils.Format("{0}_{1}", DMSDataClass.getEnumType(wDataClass).GetMysqlTablePrefixString(), wDeviceCode);
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey(wVariableName))
                    continue;


                wVariableNameTemp = StringUtils.parseString(wReader.get(wVariableName));
                if (wResult.containsKey(wVariableNameTemp))
                    continue;

                if (!wReader.containsKey(wDataLength) || StringUtils.parseInt(wReader.get(wDataLength)) < 1)
                    wReader.put(wDataLength, 20);

                if (!wReader.containsKey(wName) || StringUtils.isEmpty(StringUtils.parseString(wReader.get(wName))))
                    wReader.put(wName, wVariableNameTemp);

                wResult.put(wVariableNameTemp, wReader);
            }

            List<String> wSQLList = new ArrayList<>();
            if (!this.IsExitTable(getDBName(), wTableName)) {

//                String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
//                        " `RecordID` int NOT NULL DEFAULT ''0'', " +
//                        " PRIMARY KEY(`ID`), UNIQUE KEY `index_recordid` (`RecordID`)" +
//                        ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);

                String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
                        " `RecordID` int NOT NULL DEFAULT ''0'', " +
                        " PRIMARY KEY(`ID`),  KEY `index_recordid` (`RecordID`)" +
                        ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);

                if (wDataClass == DMSDataClass.TechnologyData.getValue() || wDataClass == DMSDataClass.Params.getValue()) {
                    wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT, " +
                            "`CreateTime` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `AssetNo` varchar(45) NOT NULL DEFAULT ''0'' , " +
                            " PRIMARY KEY(`ID`),   KEY `index_ID` (`ID`,`AssetNo`,`CreateTime`), KEY `index_AssetNo` (`AssetNo`)" +
                            ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);
                }

                this.Execute(StringUtils.splitList(wCreateSql, ";", true));
            }

            List<String> wOwnList = this.QueryTableStruct(this.SQLType, wTableName, getDBName());
            if (wOwnList != null && wOwnList.size() > 0) {
                for (String wString : wOwnList) {
                    if (wResult.containsKey(wString))
                        wResult.remove(wString);
                }
            }

            List<String> wFieldList = new ArrayList<String>();

            for (String wColName : wResult.keySet()) {
                switch (this.SQLType) {
                    case Default:
                    case MySQL:
                        wFieldList.add(StringUtils.Format(" ADD COLUMN `{0}` {1} NOT NULL DEFAULT {3} COMMENT ''{2}'' ", wColName,
                                DMSDataTypes.getEnumTypeObject(wResult.get(wColName).get(wDataType)).GetMysqlTypeStringObject(wResult.get(wColName).get(wDataLength)), wResult.get(wColName).get(wName),
                                DMSDataTypes.getEnumTypeObject(wResult.get(wColName).get(wDataType)).GetMysqlDefaultString()));
                        break;
                    case SQLServer:
                        wFieldList.add(StringUtils.Format(" ADD [{0}] NVARCHAR({1}) NOT NULL DEFAULT ''''", wColName, wResult.get(wColName).get(wDataLength)));
                        break;
                    case Oracle:
                        break;
                    case Access:
                        break;
                    default:
                        break;
                }


            }
            if (wFieldList.size() <= 0)
                return;


            String wSql = StringUtils.Format("ALTER TABLE {0}.{1} {2};", getDBName(), wTableName, StringUtils.Join(",", wFieldList));

            this.update(wSql, new HashMap<>());

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_InitDeviceTable", e);
        }
    }

    public void DMS_InitDeviceTable(BMSEmployee wLoginUser, int wModelID, String wDeviceCode, OutResult<Integer> wErrorCode) {

        try {
            if (wModelID <= 0 || StringUtils.isEmpty(wDeviceCode))
                return;


            Map<String, Map<String, Object>> wResult = new HashMap<String, Map<String, Object>>();

            String wTableName = StringUtils.Format("dms_device_processrecord_{0}", wDeviceCode);
            String wTableName1 = "";
            if (!this.IsExitTable(getDBName(), wTableName)) {

                String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
                        " `AssetNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''采集编号'', " +
                        " `MetroNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''车号''," +
                        "   `WorkpieceNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''工件编号''," +
                        "`StartTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''开始时间''," +
                        " `EndTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''结束时间'', " +
                        " `Active` tinyint NOT NULL DEFAULT ''0'' COMMENT ''激活状态''," +
                        " `Status` tinyint NOT NULL DEFAULT ''0'' COMMENT ''状态'', " +
                        " `Remark` varchar(128) NOT NULL DEFAULT '''' COMMENT ''备注'', " +
                        "`EditTime` datetime NOT NULL DEFAULT ''2000-01-01 00:00:00'', " +
                        " `RecordType` tinyint NOT NULL DEFAULT ''1'', " +
                        " `TechnologyID` int NOT NULL DEFAULT ''0'', " +
                        "  `SFCOrderID` int NOT NULL DEFAULT ''0'' COMMENT ''工单ID'', " +
                        "  `OrderID` int NOT NULL DEFAULT ''0'' COMMENT ''订单ID'', " +
                        "  `UploadStatus` int NOT NULL DEFAULT ''0'' COMMENT ''上传状态'', " +
                        "  PRIMARY KEY (`ID`) USING BTREE," +
                        "    KEY `Index_WorkPart` (`WorkpieceNo`,`StartTime`,`EndTime`,`Active`,`Status`,`AssetNo`,`OrderID`) USING BTREE," +
                        "    KEY `Index_Order` (`OrderID`)," +
                        "    KEY `Index_techno` (`TechnologyID`)," +
                        "    KEY `Index_Device` (`AssetNo`,`OrderID`,`TechnologyID`,`WorkpieceNo`,`Status`,`RecordType`,`EndTime`,`StartTime`,`Active`) USING BTREE," +
                        "    KEY `Index_Process` (`EndTime`,`StartTime`,`Active`)" +
                        ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);

                this.Execute(StringUtils.splitList(wCreateSql, ";", true));
            }
            if (wModelID == 1 || wModelID == 3) {
                wTableName1 = StringUtils.Format("dms_device_toolrecord_{0}", wDeviceCode);
                if (!this.IsExitTable(getDBName(), wTableName1)) {

                    String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
                            " `AssetNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''采集编号'', " +
                            " `MetroNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''车号''," +
                            "   `WorkpieceNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''工件编号''," +
                            "`StartTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''开始时间''," +
                            " `EndTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''结束时间'', " +
                            " `Active` tinyint NOT NULL DEFAULT ''0'' COMMENT ''激活状态''," +
                            " `Status` tinyint NOT NULL DEFAULT ''0'' COMMENT ''状态'', " +
                            " `Remark` varchar(128) NOT NULL DEFAULT '''' COMMENT ''备注'', " +
                            "`EditTime` datetime NOT NULL DEFAULT ''2000-01-01 00:00:00'', " +
                            " `RecordType` tinyint NOT NULL DEFAULT ''1'', " +
                            " `TechnologyID` int NOT NULL DEFAULT ''0'', " +
                            "  `OrderID` int NOT NULL DEFAULT ''0'' COMMENT ''工单ID'', " +
                            "  PRIMARY KEY (`ID`) USING BTREE," +
                            "    KEY `Index_WorkPart` (`WorkpieceNo`,`StartTime`,`EndTime`,`Active`,`Status`,`AssetNo`,`OrderID`) USING BTREE," +
                            "   KEY `Index_Order` (`OrderID`)," +
                            "    KEY `Index_techno` (`TechnologyID`)," +
                            "    KEY `Index_Device` (`AssetNo`,`OrderID`,`TechnologyID`,`WorkpieceNo`,`Status`,`RecordType`,`EndTime`,`StartTime`,`Active`) USING BTREE," +
                            "    KEY `Index_Process` (`EndTime`,`StartTime`,`Active`)" +
                            ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName1);

                    this.Execute(StringUtils.splitList(wCreateSql, ";", true));
                }
            }
            if (wModelID == 4 || wModelID == 5 || wModelID == 7 || wModelID == 8) {
                wTableName1 = StringUtils.Format("dms_device_toolrecord_{0}", wDeviceCode);
                if (!this.IsExitTable(getDBName(), wTableName1)) {

                    String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
                            " `AssetNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''采集编号'', " +
                            " `MetroNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''车号''," +
                            "   `WorkpieceNo` varchar(45) NOT NULL DEFAULT '''' COMMENT ''工件编号''," +
                            "`StartTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''开始时间''," +
                            " `EndTime` datetime(3) NOT NULL DEFAULT ''2000-01-01 00:00:00.000'' COMMENT ''结束时间'', " +
                            " `Active` tinyint NOT NULL DEFAULT ''0'' COMMENT ''激活状态''," +
                            " `Status` tinyint NOT NULL DEFAULT ''0'' COMMENT ''状态'', " +
                            " `Remark` varchar(128) NOT NULL DEFAULT '''' COMMENT ''备注'', " +
                            "`EditTime` datetime NOT NULL DEFAULT ''2000-01-01 00:00:00'', " +
                            " `RecordType` tinyint NOT NULL DEFAULT ''1'', " +
                            " `TechnologyID` int NOT NULL DEFAULT ''0'', " +
                            "  `OrderID` int NOT NULL DEFAULT ''0'' COMMENT ''工单ID'', " +
                            "  PRIMARY KEY (`ID`) USING BTREE," +
                            "    KEY `Index_WorkPart` (`WorkpieceNo`,`StartTime`,`EndTime`,`Active`,`Status`,`AssetNo`,`OrderID`) USING BTREE," +
                            "   KEY `Index_Order` (`OrderID`)," +
                            "    KEY `Index_techno` (`TechnologyID`)," +
                            "    KEY `Index_Device` (`AssetNo`,`OrderID`,`TechnologyID`,`WorkpieceNo`,`Status`,`RecordType`,`EndTime`,`StartTime`,`Active`) USING BTREE," +
                            "    KEY `Index_Process` (`EndTime`,`StartTime`,`Active`)" +
                            ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName1);

                    this.Execute(StringUtils.splitList(wCreateSql, ";", true));
                }
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_InitDeviceTable", e);
        }
    }

    /**
     * 刀具
     *
     * @param wLoginUser
     * @param wDataClass
     * @param wDataGrad
     * @param wDeviceID
     * @param wDeviceCode
     * @param wModelID
     * @param wErrorCode
     */
    public void DMS_InitDeviceTable(BMSEmployee wLoginUser, int wDataClass, int wDataGrad, int wDeviceID, String wDeviceCode, int wModelID, OutResult<Integer> wErrorCode) {

        try {
            if (wDataClass <= 0 || wDeviceID <= 0 || StringUtils.isEmpty(wDeviceCode))
                return;
            if (wModelID != 1 && wModelID != 3 && wModelID != 4 && wModelID != 5 && wModelID != 7 && wModelID != 8)
                return;

            String wVariableName = "VariableName";
            String wDataLength = "DataLength";
            String wName = "Name";
            String wDataType = "DataType";


            String wSQL = StringUtils.Format("SELECT t.{1},t.{2},t.{3},t.{4}  FROM {0}.dms_device_parameter t " +
                            " inner join {0}.dms_device_ledger t1 on t.DeviceID=t1.ID AND t1.Active=1" +
                            " where t.ID>0 AND  t.DataClass=:wDataClass  and t1.ID= :wDeviceID  " +
                            " and (:wDataGrad <0 or t.DataGrad=:wDataGrad ) " +
                            " and t.Active=1 group by t.VariableName;",
                    getDBName(), wVariableName, wDataLength, wName, wDataType);
            Map<String, Object> wParamMap = new HashMap<String, Object>();
            wParamMap.put("wDataClass", wDataClass);
            wParamMap.put("wDataGrad", wDataGrad);
            wParamMap.put("wDeviceID", wDeviceID);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);

            if (wQueryResult.size() <= 0)
                return;

            Map<String, Map<String, Object>> wResult = new HashMap<String, Map<String, Object>>();
            String wVariableNameTemp = "";

            String wTableName = "dms_device_toolparams_" + wDeviceCode;
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey(wVariableName))
                    continue;


                wVariableNameTemp = StringUtils.parseString(wReader.get(wVariableName));
                if (wResult.containsKey(wVariableNameTemp))
                    continue;

                if (!wReader.containsKey(wDataLength) || StringUtils.parseInt(wReader.get(wDataLength)) < 1)
                    wReader.put(wDataLength, 20);

                if (!wReader.containsKey(wName) || StringUtils.isEmpty(StringUtils.parseString(wReader.get(wName))))
                    wReader.put(wName, wVariableNameTemp);

                wResult.put(wVariableNameTemp, wReader);
            }

            if (!this.IsExitTable(getDBName(), wTableName)) {

                String wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT," +
                        " `RecordID` int NOT NULL DEFAULT ''0'', " +
                        " PRIMARY KEY(`ID`), UNIQUE KEY `index_recordid` (`RecordID`)" +
                        ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);

                if (wDataClass == ((int) DMSDataClass.TechnologyData.getValue())) {
                    wCreateSql = StringUtils.Format(" use {0}; CREATE TABLE `{1}` (  `ID` int NOT NULL AUTO_INCREMENT, " +
                            "`CreateTime` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `AssetNo` varchar(45) NOT NULL DEFAULT ''0'' , " +
                            " PRIMARY KEY(`ID`),   KEY `index_ID` (`ID`,`AssetNo`,`CreateTime`), KEY `index_AssetNo` (`AssetNo`)" +
                            ") ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_bin; ", getDBName(), wTableName);
                }

                this.Execute(StringUtils.splitList(wCreateSql, ";", true));
            }

            List<String> wOwnList = this.QueryTableStruct(this.SQLType, wTableName, getDBName());
            if (wOwnList != null && wOwnList.size() > 0) {
                for (String wString : wOwnList) {
                    if (wResult.containsKey(wString))
                        wResult.remove(wString);
                }
            }

            List<String> wFieldList = new ArrayList<String>();

            for (String wColName : wResult.keySet()) {
                switch (this.SQLType) {
                    case Default:
                    case MySQL:
                        wFieldList.add(StringUtils.Format(" ADD COLUMN `{0}` {1} NOT NULL DEFAULT {3} COMMENT ''{2}'' ", wColName,
                                DMSDataTypes.getEnumTypeObject(wResult.get(wColName).get(wDataType)).GetMysqlTypeStringObject(wResult.get(wColName).get(wDataLength)), wResult.get(wColName).get(wName),
                                DMSDataTypes.getEnumTypeObject(wResult.get(wColName).get(wDataType)).GetMysqlDefaultString()));
                        break;
                    case SQLServer:
                        wFieldList.add(StringUtils.Format(" ADD [{0}] NVARCHAR({1}) NOT NULL DEFAULT ''''", wColName, wResult.get(wColName).get(wDataLength)));
                        break;
                    case Oracle:
                        break;
                    case Access:
                        break;
                    default:
                        break;
                }


            }
            if (wFieldList.size() <= 0)
                return;


            String wSql = StringUtils.Format("ALTER TABLE {0}.{1} {2};", getDBName(), wTableName, StringUtils.Join(",", wFieldList));

            this.update(wSql, new HashMap<>());

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_InitDeviceTable", e);
        }
    }


}
